package br.inf.ufrgs.usixml4desktop.rendering;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.jdom.Element;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class ResourceRetriever {
	
	private Element resourceModel = null;
	
	public ResourceRetriever(Element resourceModel) {
		this.resourceModel = resourceModel;
	}
	
	public String getStringResourceContent(Element element){
		
		String cioId = element.getAttributeValue("id");
		String content = null;
		try {
//			Parse the XML as a W3C document.
	        DocumentBuilder builder =
	            DocumentBuilderFactory.newInstance().newDocumentBuilder();
	        Document document = builder.parse(new File("D:/frk/Projetos Software/UsiXML4ALL/UsiXML4Desktop/resources/Calculator/calculator2.usi"));
	
	        XPath xpath = XPathFactory.newInstance().newXPath();
	        String expression = "//resourceModel/cioRef[@cioId='" + cioId + "']/resource/@content";
	
	        // Next, obtain the element as a String.
	
	        content = (String)xpath.evaluate(expression, document, XPathConstants.STRING);
        
		} catch (ParserConfigurationException e) {
            System.err.println("ParserConfigurationException caught...");
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            System.err.println("XPathExpressionException caught...");
            e.printStackTrace();            
        } catch (SAXException e) {
            System.err.println("SAXException caught...");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IOException caught...");
            e.printStackTrace();
        }
		
		return content;
	}

}
